import { error } from './../../../react-manager/node_modules/ajv/lib/vocabularies/applicator/dependencies';
import { store } from '../store'
import { message } from 'antd'
import axios, { AxiosError, type AxiosRequestConfig, type AxiosResponse, type CancelTokenSource, type InternalAxiosRequestConfig } from 'axios'
import { checkStatus } from './helper/checkStatus'

let cancelTokenSource: CancelTokenSource | null = null

const axiosInstance = axios.create({
  baseURL: '',
  timeout: 10000,
  withCredentials: true,
})

axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token: string = store.getState().global.token || ''
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
},
  (error) => {
    return Promise.reject(error); //处理请求错误
  }
);

axiosInstance.interceptors.response.use((response: AxiosResponse) => {
  const { data } = response

  // 全局错误信息拦截
  if (data.code && data.code !== 200) {
    message.error(data.msg)
    return Promise.reject(data)
  }
  return data  // 成功请求
},
  (error: AxiosError) => {
    // 处理响应错误
    const {response} = error
    if (response) checkStatus(response.status)
    return Promise.reject(error)
  }
);

const Request = async <T>(method: string, url: string, dataOrParams: any = {}, shouldCancel: boolean = false): Promise<T> => {
  if (shouldCancel && cancelTokenSource) {
    (cancelTokenSource as CancelTokenSource).cancel('请求已被取消')
  }
  cancelTokenSource = axios.CancelToken.source()
  const config: AxiosRequestConfig = {
    cancelToken: cancelTokenSource.token,
  }

  try {
    const response = await axiosInstance[method.toLowerCase()]<T>(
      url,
      method.toLowerCase() === 'post' ? dataOrParams : { params: dataOrParams },
      config,
    )
    return response.data
  } catch (error) {
    if (axios.isCancel(error)) {
      console.log('请求已被取消')
      return Promise.reject()
    } else {
      console.log(error)
      throw error;
    }
  }
}

export { axiosInstance, Request }